// ## 2.编写单向链表类并且实现队列的入列出列操作。
/**
 * 节点结构
 */
class Node {
  constructor(node, next) {
    this.val = node
    this.next = next
  }
}

/**
 * 单向列表类
 */
class LinkedList {
  constructor(head, size) {
    this.head = head || null
    this.size = size || 0
  }
  // 获取节点内容
  _getNode(index) {
    if (index < 0 || index > this.size) {
      throw new Error('超出节点范围')
    }
    let currentNode = this.head
    for (let i = 0; i < index; i++) {
      currentNode = currentNode.next
    }
    return currentNode
  }
  // 添加节点
  add(index, node) {
    if (arguments.length === 1) {
      node = index
      index = this.size
    }
    if (index < 0 || index > this.size) {
      throw new Error('corss the border')
    }
    if (index === 0) {
      let head = this.head
      this.head = new Node(node, head)
    } else {
      let prevNode = this._getNode(index - 1)
      prevNode.next = new Node(node, prevNode.next)
    }
    this.size++
  }
  remove(index) {
    let rmNode = null
    if (index === 0) {
      rmNode = this.head
      if (!rmNode) return undefined
      this.head = rmNode.next
    } else {
      let prevNode = this._getNode(index - 1)
      rmNode = prevNode.next
      this.head.next = rmNode.next
    }
    this.size--
    return rmNode
  }
  set(index, node) {
    let currentNode = this._getNode(index)
    currentNode.val = node
  }
  get(index) {
    return this._getNode(index)
  }
  // 清空类节点
  clear () {
    this.head = null
    this.size = 0
  }
}

class Queue {
  constructor() {
    this.linkedList = new LinkedList()
  }
  enQueue(data) {
    this.linkedList.add(data)
  }
  deQueue() {
    return this.linkedList.remove(0)
  }
}

// const list = new Queue()
// list.enQueue(1)
// list.enQueue(2)
// list.enQueue(3)
// console.dir(list)
// list.deQueue()
// console.log(list)

module.exports = Queue